// gitreview.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var app = getApp();
var range
var winScale = 750 / app.data.deviceInfo.windowWidth
var revcontent = {}
var revimage = {}
var pages, prevPage
var revrating_level = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popflag: false,
    pullflag: true,//只允许提交一次
    showLoading: true,
    reviewtabs: ['好评', '中评', '差评'],
    pictures: [],
    pictureslist: {},
    picturesCount: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) { //git_review get_review_product
    var that = this;
    range = 1030 / winScale;
    var animation = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    pages = getCurrentPages();
    if (pages.length >= 2) {
      prevPage = pages[pages.length - 2];
    }
    shihan.sendRequest(config.get_review_product, 'POST', {
        order_no: options.order_no
      }, {})
      .then(function(response) {
        // response.data.data["sh_products"] = [
        //   {
        //     "sh_order_product_id": 9147,
        //     "sh_product_id": 25872,
        //     "sh_name": "丹溪纯酿500ml",
        //     "sh_image": "https:\/\/img-oss.shihanbainian.com\/\/upload_dev\/product\/f\/0\/f\/f0fe6cfdba499013c5018e91f8f2534d.jpg?x-oss-process=image\/resize,m_fixed,w_300",
        //     "sh_attributes": [
        //       {
        //         "sh_attribute_label": "规格",
        //         "sh_alias_name": "500ml"
        //       }
        //     ]
        //   },
        //   {
        //     "sh_order_product_id": 9147,
        //     "sh_product_id": 25872,
        //     "sh_name": "丹溪纯酿500ml",
        //     "sh_image": "https:\/\/img-oss.shihanbainian.com\/\/upload_dev\/product\/f\/0\/f\/f0fe6cfdba499013c5018e91f8f2534d.jpg?x-oss-process=image\/resize,m_fixed,w_300",
        //     "sh_attributes": [
        //       {
        //         "sh_attribute_label": "规格",
        //         "sh_alias_name": "500ml"
        //       }
        //     ]
        //   },
        //   {
        //     "sh_order_product_id": 9147,
        //     "sh_product_id": 25872,
        //     "sh_name": "丹溪纯酿500ml",
        //     "sh_image": "https:\/\/img-oss.shihanbainian.com\/\/upload_dev\/product\/f\/0\/f\/f0fe6cfdba499013c5018e91f8f2534d.jpg?x-oss-process=image\/resize,m_fixed,w_300",
        //     "sh_attributes": [
        //       {
        //         "sh_attribute_label": "规格",
        //         "sh_alias_name": "500ml"
        //       }
        //     ]
        //   }
        // ]
        for (var i = 0; i < response.data.data.sh_products.length; i++) {
          response.data.data.sh_products[i].sh_currentTab = 0;
          var goodsid = response.data.data.sh_products[i].sh_order_product_id
          revrating_level[goodsid] = 1
          // revcontent[goodsid] = ''
          that.data.pictureslist[goodsid] = []
          that.data.picturesCount[goodsid] = 4
        }
        that.setData({
          showLoading: false,
          present: options.present,
          revrating_level: revrating_level,
          pictureslist: that.data.pictureslist,
          reviewcontent: {},
          order_no: options.order_no,
          review_product: response.data.data
        });

      }, function(error) {
        console.log(error);
      });
  },
  tabClick: function(e) {
    var index = e.currentTarget.dataset.index
    var goodsid = e.currentTarget.dataset.goodsid
    this.data.revrating_level[goodsid] = Number(e.currentTarget.id) + 1
    this.data.review_product.sh_products[index].sh_currentTab = e.currentTarget.id
    this.setData({
      revrating_level: this.data.revrating_level,
      review_product: this.data.review_product
    })
  },
  uploadImg: function(e) {
    var that = this;
    var revpictures = [];
    var token = wx.getStorageSync('token');
    var open_id = wx.getStorageSync('open_id');
    var goodsid = e.currentTarget.dataset.goodsid;
    wx.chooseImage({
      count: that.data.picturesCount[goodsid],
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        // console.log(tempFilePaths)
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: config.commonapi + '1/helper/upload',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              'type': 'review',
              'device': open_id,
              'token': token,
              'version': config.version
            },
            success: function(res) {
              var response = JSON.parse(res.data)
              var obj = that.data.pictureslist[goodsid]
              obj.unshift(response.data.sh_image_url)
              that.data.picturesCount[goodsid] = 4 - Number(obj.length)
              that.setData({
                pictureslist: that.data.pictureslist,
                picturesCount: that.data.picturesCount,
              })
            },
            fail: function(res) {
              console.log("fail", res);
            },
          })
        }
      }
    })
  },
  deleteimg: function(e) {
    var index = e.currentTarget.dataset.index
    var goodsid = e.currentTarget.dataset.goodsid
    var obj = this.data.pictureslist[goodsid]
    console.log(obj.length);
    obj.splice(index, 1)
    this.setData({
      pictureslist: this.data.pictureslist
    })
  },
  pullreview: function() {
    var that = this, gitflag = false, data = {};

    data['content'] = JSON.stringify(this.data.reviewcontent) //评价内容
    data['image'] = JSON.stringify(this.data.pictureslist) //评价图片
    data['rating_level'] = JSON.stringify(this.data.revrating_level) //评价等级
    data['order_no'] = this.data.order_no //评价订单号
    console.log(data)
    for (var i in this.data.reviewcontent) {
      if (this.data.reviewcontent[i]) {
        gitflag = true
      }
    }
    if (!gitflag) {
      shihan.showToast.call(that, '请至少填写一条评价哦');
      return;
    }
    if (that.data.pullflag) {
      that.setData({
        pullflag: false
      })
      shihan.sendRequest(config.git_review, 'POST', data, {})
        .then(function (response) {
          // console.log(response)
          if (response.data.code == 0) {
            shihan.showToast.call(that, '提交评价成功');
            setTimeout(function () {
              wx.navigateBack()
            }, 1000)
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
          prevPage.setData({
            refreshflag: true
          })
        }, function (error) {
          console.log(error);
        });
    }
  },
  openpop: function(e) {
    this.animation.translateY(-range).step();
    this.setData({
      popflag: true,
      animationData: this.animation.export(),
      currentgoodsid: e.currentTarget.dataset.goodsid
    })
  },
  confirmbtn: function(e) {
    var goodsid = e.currentTarget.dataset.goodsid
    this.animation.translateY(range).step();
    this.data.reviewcontent[goodsid] = this.data.presentcontent
    this.setData({
      popflag: false,
      animationData: this.animation.export(),
      reviewcontent: this.data.reviewcontent
    })
  },
  canclebtn: function() {
    this.animation.translateY(range).step();
    this.setData({
      popflag: false,
      animationData: this.animation.export()
    })
  },
  getreviewwords: function(e) {
    var goodsid = e.currentTarget.dataset.goodsid;
    this.data.reviewcontent[goodsid] = e.detail.value;
    this.setData({
      reviewcontent: this.data.reviewcontent
    })
  },
  // content	评价内容{"订单商品id": "评价内容" }	string	{"11": "东西不错", "12": "东西好" }
  // image	图片{"订单商品id": ["img1", "img2"] }	string	{"11": ["img1", "img2"], "12": ["img3", "img4"] }
  // order_no	订单号	string	O201707201122032132
  // rating_level	等级{"订单商品id": "1" }	string	{"11": "1", "12": "2" }
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    revcontent = {}
    revimage = {}
    revrating_level = {}
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    revcontent = {}
    revimage = {}
    revrating_level = {}
  }
})